package com.gmlive.plugin.jenkins

import org.gradle.api.Project
import java.io.File
import java.security.MessageDigest

object JenkinsUtils {

    fun requireProperty(project: Project, key: String): String {
        val value = project.properties.getOrDefault(key, "").toString()
        if (value.isEmpty()) {
            //            throw new GradleException("属性: ${key} 的值不能为空")
        }
        return value
    }

    fun md5Sum(file: File): String {
        val md = MessageDigest.getInstance("MD5")
        file.forEachBlock(4096) { bytes, size ->
            md.update(bytes, 0, size)
        }

        return md.digest().map { String.format("%02x", it) }.joinToString(separator = "") { it }
    }

    fun fileSize(file: File): String {
        val size = file.length() / 1024.0 / 1024.0

        return String.format("%.2fM", size)
    }

    fun String?.toUpperCaseFirst(): String = takeIf { !isNullOrEmpty() }?.run {
        replaceFirst(
            oldChar = first(),
            newChar = first().toUpperCase(),
            ignoreCase = true
        )
    } ?: this ?: ""

    fun extractApks(project: Project, options: JenkinsOptions, output: String): Boolean {
        val toolPath = System.getenv("BUNDLE_TOOL_PATH")
        println("[Jenkins] ExtractApks>> $output")
        val extraCmd = "java -jar " + toolPath +
                " build-apks" +
                " --bundle=${options.srcAABFile}" +
                " --output=${output}" +
                " --ks=${options.signConfig.storeFile!!.absolutePath}" +
                " --ks-pass=pass:${options.signConfig.storePassword}" +
                " --ks-key-alias=${options.signConfig.keyAlias}" +
                " --key-pass=pass:${options.signConfig.keyPassword}"
        val javaHome = System.getenv("JAVA_HOME")
        val cmd = listOf(
            "-c",
            "export JAVA_HOME=$javaHome/;" +
                    "export JRE_HOME=\${JAVA_HOME}/jre;" +
                    "export CLASSPATH=.:\${JAVA_HOME}/lib:\${JRE_HOME}/lib;" +
                    "export PATH=.:\${JAVA_HOME}/bin:\$PATH;" +
                    "java -version;" +
                    extraCmd
        )
        return try {
            project.exec {
                it.setCommandLine("bash")
                it.args = cmd
            }
            true
        } catch (e: Exception) {
            println("[Jenkins] ExtractApks>> failed: $e")
            false
        }
    }
}